let ChatContentModel = require('../model').chatContentModel;
let DaoTool = require('../lib/daoTool');

exports.createChatContent = function (conn,params) {
    return new Promise(function (resolve, reject) {
        let sql = "insert into chat_content set ?";
        conn.query(sql, [DaoTool.generateModelObject(params, ChatContentModel, 'create')], function (err, result) {
            printLog("=createChatContent=", this.sql);
            if (err) reject(err);
            resolve(result)
        });
    });
};
exports.selectLastContent = function (conn,params) {
    return new Promise(function (resolve, reject) {
        conn.query('select ChatNo,ChatContent,CreatedAt from chat_content where ChatNo = ? ORDER BY ChatContentId desc limit 0,1;', [params.ChatNo], function (err, result) {
            printLog("=selectLastContent=", this.sql);
            if (err) reject(err);
            resolve(result)
        });
    });
};
exports.selectChatContent = function (conn,params,isCount) {
    return new Promise(function (resolve, reject) {
        let sql = " from chat as cht LEFT JOIN chat_content as chc on chc.ChatNo=cht.ChatNo LEFT JOIN user as u on u.openid=chc.openid where cht.ChatNo=?" + formatQueryWhere(params) + " order by chc.ChatContentId desc  ";
        let selectSql = "select * from (select chc.*,u.NickName,u.HeadImgUrl " + sql +DaoTool.getPageParamsSqlStr(params)+") as result order by result.ChatContentId asc;";
        console.log(selectSql);
        let countSql = "select count(1) as num" + sql;
        conn.query(selectSql, [params.ChatNo], function (err, selectResult) {
            printLog("=selectChatContent err=",err);
            printLog("=selectChatContent=",this.sql);
            if (err) reject(err);
            if (!isCount) resolve(selectResult);
            conn.query(countSql,[params.ChatNo],function (err,countResult) {
                printLog("=selectChatContent err=",err);
                printLog("=selectChatContent=",this.sql);
                if (err) reject(err);
                resolve({data:selectResult,count:countResult[0].num});
            });
        });
    });
};

var formatQueryWhere = function (params) {
    var sql = ''
    if (params.lastChatContentId) {
        sql = ' and chc.ChatContentId > ' + params.lastChatContentId
    }
    return sql
}

exports.countChatContent = function (conn,params) {
    return new Promise(function (resolve, reject) {
        conn.query('select count(*) as num from chat_content where ChatNo=? and openid=?;', [params.ChatNo,params.openid], function (err, result) {
            printLog("=countChatContent=", this.sql);
            if (err) reject(err);
            resolve(result[0].num);
        });
    });
};